//
//  AppDelegate.m
//  FuncFanc
//
//  Created by hubing on 2018/3/5.
//  Copyright © 2018年 huhu. All rights reserved.
//  数据备份指导。 将app备份至 itunes ，然后恢复到新设备。
//  没有网络请求，所有数据只存本地，不会被同步到其他地方。你的数据只属于你。
//
//

#import "AppDelegate.h"
#import "CenterTabBarController.h"
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>

@interface AppDelegate ()
// 监测 app在后台留存时间。结论： iPhone XR iOS14.5系统， app在后台留存 30s。
//@property (nonatomic,strong) NSTimer *backTimer;

//@property (nonatomic,assign) NSInteger bgSeconds;

//循环播放一段无声音乐，让app持续在后台留存。
//@property (nonatomic,strong) AVAudioSession *session;

//@property (nonatomic,strong) AVAudioPlayer *player;


@end

@implementation AppDelegate

+ (instancetype)sharedAppDelegate
{
    return (AppDelegate *)[UIApplication sharedApplication].delegate;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
//    InstallUncaughtExceptionHandler();// 拦截崩溃.
//    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
//    [formatter setDateFormat:@"yyyy-MM-D"];
//    NSString * dateNow = [formatter stringFromDate:[NSDate date]];
    
    
//    NSDateFormatter *formatter2 = [[NSDateFormatter alloc]init];
//    [formatter2 setDateFormat:@"yyyy-MM-DD"];
//    NSString * dateNow2 = [formatter2 stringFromDate:[NSDate date]];
    
    
//    SDImageWebPCoder *webPCoder = [SDImageWebPCoder sharedCoder];
//    [[SDImageCodersManager sharedManager] addCoder:webPCoder]
//    _bgSeconds = 0;
//    NSString *errStr = [NSString stringWithFormat:@"当前%@版本%@，返回为NULL",@"",@""];
//    NSError *error = [NSError errorWithCode:1001 description:errStr];
    
    self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    
    CenterTabBarController *tabBar = [[CenterTabBarController alloc]init];
    
    self.window.rootViewController = tabBar;
    
    NSString *number = [[NSUserDefaults standardUserDefaults] stringForKey:@"SBFormattedPhoneNumber"];
    NSLog(@"%@",number);
    [self.window makeKeyAndVisible];
    
    [self configCommonProperty];
    [self addFloatView];
    
    [QHHCPFileManager copySoundFileToDocument];
    
    return YES;
}

-(void)addFloatView
{
    _floatView = [FloatingView sharedView];
    [self.window addSubview:_floatView];
    [_floatView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-20);
        make.bottom.mas_equalTo(-80);
        make.width.height.mas_equalTo(60);
    }];
}

-(void)configCommonProperty
{
    [UITableViewCell appearance].selectionStyle = UITableViewCellSelectionStyleNone;
    [UINavigationBar appearance].barStyle = UIBarStyleBlack;
    [[UINavigationBar appearance] setBarTintColor:NAVI_BAR_SKYBLUE];
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    [UINavigationBar appearance].translucent = NO;
    [[UINavigationBar appearance] setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:19],
       NSForegroundColorAttributeName:RGBOF(0xfdfdfd)}];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
           
    application.applicationIconBadgeNumber = 0;

//    UIUserNotificationSettings *set = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil];
//    [[UIApplication sharedApplication] registerUserNotificationSettings:set];
//    [[UIApplication sharedApplication]registerForRemoteNotifications];
//    [self playbackground];
//    __weak typeof(self) ws = self;
//    self.backTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
//        ws.bgSeconds += 1;
//        application.applicationIconBadgeNumber = ws.bgSeconds;
//        DebugLog(@"%ld",application.applicationIconBadgeNumber);
//    }];
//    [application beginBackgroundTaskWithExpirationHandler:^{
//
//    }];
    
}


// 不推荐的方法，审核会被拒绝。
//-(void)playbackground
//{
//    _session = [AVAudioSession sharedInstance];
//    [[AVAudioSession sharedInstance]setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
//    [_session setActive:YES error:nil];
//    NSString *musicPath = [[NSBundle mainBundle] pathForResource:@"sound_call_incoming" ofType:@"mp3"];
//    NSURL *URLPath = [[NSURL alloc] initFileURLWithPath:musicPath];
//    _player = [[AVAudioPlayer alloc]initWithContentsOfURL:URLPath error:nil];
//    [_player prepareToPlay];
//    _player.volume = 0.0;
//    _player.numberOfLoops = -1;
//    [_player play];
//    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(audioSessionInterruptionNotification:) name:AVAudioSessionInterruptionNotification object:nil];
//}
//
//-(void)audioSessionInterruptionNotification:(NSNotification *)notification
//{
//    int type = [notification.userInfo[AVAudioSessionInterruptionOptionKey]intValue];
//    switch (type) {
//        case AVAudioSessionInterruptionTypeBegan:
//            [_player pause];
//            break;
//        case AVAudioSessionInterruptionTypeEnded:
//            [_player play];
//            break;
//        default:
//            break;
//    }
//}


-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    
}



- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    @autoreleasepool
    {
        viewController.hidesBottomBarWhenPushed = YES;
        viewController.navigationController.navigationBar.hidden = YES;
        [[self navigationViewController] pushViewController:viewController animated:animated];
    }
}

- (void)presentViewController:(UIViewController *)viewController animated:(BOOL)animated completion:(void (^ __nullable)(void))completion
{
    @autoreleasepool
    {
        [[self navigationViewController] presentViewController:viewController animated:animated completion:completion];
    }
}

// 获取当前活动的navigationcontroller
- (UINavigationController *)navigationViewController
{
    if ([self.window.rootViewController isKindOfClass:[UINavigationController class]])
    {
        return (UINavigationController *)self.window.rootViewController;
    }
    else if ([self.window.rootViewController isKindOfClass:[UITabBarController class]])
    {
        UIViewController *selectVc = [((UITabBarController *)self.window.rootViewController) selectedViewController];
        if ([selectVc isKindOfClass:[UINavigationController class]])
        {
            return (UINavigationController *)selectVc;
        }
    }
    return nil;
}


@end
